﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessServices;
using Core.Utilities;
using DataEntities;

namespace CarLeaseManageSystem
{
    public partial class FormTHMana : Form
    {
        private readonly TuiHuanService _tuiHuanService;
        private readonly KeHuService _keHuService;
        private readonly ChuZuService _chuZuService;
        private readonly XuZuService _xuZuService;
        private readonly WeiZhangService _weiZhangService;
        private List<KeHuInfo> _keHuInfoCache;
        private BindingSource _bindingSource;

        public FormTHMana()
        {
            _tuiHuanService = new TuiHuanService();
            _keHuService = new KeHuService();
            _chuZuService = new ChuZuService();
            _xuZuService = new XuZuService();
            _weiZhangService = new WeiZhangService();
            _keHuInfoCache = new List<KeHuInfo>();
            InitializeComponent();
        }

        private void FormTHMana_Load(object sender, EventArgs e)
        {
            comBoxArea.SelectedIndex = 0;
        }

        private void comBoxArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<KeHuInfo> keHuInfos;
            switch (comBoxArea.SelectedIndex)
            {
                case 0:
                    keHuInfos = _keHuService.GetKeHuInfoWhereChuZuTimeOut();
                    break;
                case 1:
                    keHuInfos = _keHuService.GetKeHuInfoWhereChuZuNotTimeOut();
                    break;
                default:
                    keHuInfos = _keHuService.GetKeHuInfoWhereChuZuClosed();
                    break;
            }
            _keHuInfoCache.Clear();
            listViewExist.Items.Clear();
            foreach (KeHuInfo keHuInfo in keHuInfos)
            {
                var name = string.Format("{0}({1})", keHuInfo.sName, keHuInfo.sIdCard.Substring(14, 4));
                var cItem = new ListViewItem { Tag = keHuInfo.iKeHuId, Text = name };
                listViewExist.Items.Add(cItem);
                _keHuInfoCache.Add(keHuInfo);
            }
        }

        private void ShowXuZuDetail(object sender, EventArgs e)
        {
            panelXZ.Visible = !panelXZ.Visible;
        }

        private void listViewExist_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (!e.IsSelected)
            {
                return;
            }

            var keHuId = (int)e.Item.Tag;
            if (comBoxArea.SelectedIndex == 2)
            {
                ShowBill(keHuId);
                btnOk.Enabled = false;
                bindingNavigator.Enabled = true;
            }
            else
            {
                btnOk.Enabled = true;
                bindingNavigator.Enabled = false;
                try
                {
                    //出租信息 
                    var chuZuInfo = LoadChuZuInfo(keHuId);

                    //续租信息
                    if (chuZuInfo.bXZ)
                    {
                        LoadXuZuInfo(chuZuInfo.iCZDId);
                    }
                    else
                    {
                        txtMore.Text = "(该客户无续租记录)\r\n";
                        numXZDays.Value = default(decimal);
                        numXZJE.Value = default(decimal);
                    }

                    //违章信息
                    LoadWeiZhangInfo(chuZuInfo.iCZDId);

                    CalculateMoney();
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                }
            }
        }

        //显示指定客户的历史账单
        private void ShowBill(int keHuId)
        {
            var tuiHuanInfo = _tuiHuanService.GetAllByKeHuId(keHuId);
            _bindingSource = new BindingSource();
            ClearDataBindings();

            _bindingSource.DataSource = tuiHuanInfo;
            bindingNavigator.BindingSource = _bindingSource;

            txtName.DataBindings.Add(new Binding("Text", _bindingSource, "KeHuInfo.sName"));
            txtCar.DataBindings.Add(new Binding("Text", _bindingSource, "CarInfo.sCType"));
            dateStart.DataBindings.Add(new Binding("Value", _bindingSource, "tStartDate"));
            dateEnd.DataBindings.Add(new Binding("Value", _bindingSource, "tEndDate"));
            dateJSRQ.DataBindings.Add(new Binding("Value", _bindingSource, "tJSRQ"));
            numYuFu.DataBindings.Add(new Binding("Value", _bindingSource, "dYuFuJE"));
            numYJ.DataBindings.Add(new Binding("Value", _bindingSource, "dYaJing"));
            numRF.DataBindings.Add(new Binding("Value", _bindingSource, "dRiFu"));
            numYH.DataBindings.Add(new Binding("Value", _bindingSource, "dYouHui"));
            numSFJE.DataBindings.Add(new Binding("Value", _bindingSource, "dShiFu"));
            numCZDays.DataBindings.Add(new Binding("Value", _bindingSource, "iCZDays"));
            numXZDays.DataBindings.Add(new Binding("Value", _bindingSource, "iXZDays"));
            numXZJE.DataBindings.Add(new Binding("Value", _bindingSource, "dXuZuSF"));
            numYFJE.DataBindings.Add(new Binding("Value", _bindingSource, "dYingFu"));
            numYT.DataBindings.Add(new Binding("Value", _bindingSource, "dYT"));
            numYS.DataBindings.Add(new Binding("Value", _bindingSource, "dYS"));
            txtMore.DataBindings.Add(new Binding("Text", _bindingSource, "sMore"));
            Binding imgBinding = new Binding("Image", _bindingSource, "imgKC");
            imgBinding.Format += new ConvertEventHandler(ConvertImage);
            pictPhoto.DataBindings.Add(imgBinding);
        }

        //清除数据绑定
        private void ClearDataBindings()
        {
            txtName.DataBindings.Clear();
            txtCar.DataBindings.Clear();
            dateStart.DataBindings.Clear();
            dateEnd.DataBindings.Clear();
            dateJSRQ.DataBindings.Clear();
            numYuFu.DataBindings.Clear();
            numYJ.DataBindings.Clear();
            numRF.DataBindings.Clear();
            numYH.DataBindings.Clear();
            numSFJE.DataBindings.Clear();
            numCZDays.DataBindings.Clear();
            numXZDays.DataBindings.Clear();
            numXZJE.DataBindings.Clear();
            numYFJE.DataBindings.Clear();
            numYT.DataBindings.Clear();
            numYS.DataBindings.Clear();
            txtMore.DataBindings.Clear();
            pictPhoto.DataBindings.Clear();

        }

        //转换汽车照片二进制数据为图片
        private void ConvertImage(object sender, ConvertEventArgs e)
        {
            e.Value = ((Binary)e.Value).ToImage();
        }

        //计算费用
        private void CalculateMoney()
        {
            numYFJE.Value = (numXZDays.Value + numCZDays.Value) * numRF.Value;
            numYS.Value = numYFJE.Value + numWZ.Value - numYH.Value;
            numYT.Value = numYuFu.Value + numYJ.Value + numSFJE.Value + numXZJE.Value - numYS.Value;
        }

        //加载出租信息
        private ChuZuInfo LoadChuZuInfo(int keHuId)
        {
            var chuZuInfo = _chuZuService.GetActiveChuZuInfoByKeHuId(keHuId);
            labTHInfo.Tag = chuZuInfo.iCZDId;
            txtName.Text = chuZuInfo.KeHuInfo.sName;
            txtName.Tag = chuZuInfo.iKeHuId;
            txtCar.Text = chuZuInfo.CarInfo.sCType;
            txtCar.Tag = chuZuInfo.iCarid;
            Image keHuImg = chuZuInfo.KeHuInfo.mPhoto.ToImage();
            pictPhoto.Image = chuZuInfo.CarInfo.mCPhoto.ToImage().MergeImg(keHuImg);
            dateStart.Value = chuZuInfo.tStartDate;
            dateEnd.Value = chuZuInfo.tEndDate;
            numYuFu.Value = (decimal)chuZuInfo.dYuFuJE;
            numYJ.Value = (decimal)chuZuInfo.dYaJing;
            numRF.Value = (decimal)chuZuInfo.dRiFuJE;
            numYH.Value = (decimal)chuZuInfo.dYouHuiJE;
            numSFJE.Value = (decimal)chuZuInfo.dShiFuJE;
            numCZDays.Value = Decimal.Round((Decimal)(dateEnd.Value - dateStart.Value).TotalDays, 0);
            numYFJE.Value = numRF.Value * numCZDays.Value;

            if (dateEnd.Value == DateTime.Now.Date)
            {
                labStatu.Text = "已到期";
                dateJSRQ.Enabled = false;
            }
            else if (dateEnd.Value < DateTime.Now.Date)
            {
                labStatu.Text = "已超期";
                dateJSRQ.Enabled = true;
            }
            else
            {
                labStatu.Text = "出租中...";
                dateJSRQ.Enabled = true;
            }
            return chuZuInfo;
        }

        //加载续租信息
        private void LoadXuZuInfo(int czdId)
        {
            var xuZuInfo = _xuZuService.GetXuZuInfoByChuZuId(czdId).OrderBy(x => x.tNewDate);
            var sb = new StringBuilder();
            var i = 1;
            if (xuZuInfo.Count() > 0)
            {
                var xzje = default(decimal);
                foreach (XuZuInfo xz in xuZuInfo)
                {
                    var days = (xz.tNewDate - xz.tOldDate).Days;
                    sb.AppendFormat("===========续租{0}===========\r\n", i);
                    sb.AppendFormat("日期:{0:d}\r\n天数:{1}天\t续租金:{2}元\r\n", xz.tNewDate, days, xz.dXZJE);
                    numXZDays.Value += days;
                    xzje += (decimal)xz.dXZJE;
                    i++;
                }
                sb.Append("\r\n(如提前还车,以上信息无效)\r\n");
                numXZJE.Value = xzje;
                txtMore.Text = sb.ToString();
                dateEnd.Value = xuZuInfo.Last().tNewDate;
                if (dateEnd.Value.Date == DateTime.Now.Date)
                {
                    labStatu.Text = "已到期";
                    dateJSRQ.Enabled = false;
                }
                else if (dateEnd.Value < DateTime.Now)
                {
                    labStatu.Text = "已超期";
                    dateJSRQ.Enabled = true;
                }
                else
                {
                    labStatu.Text = "续租中...";
                    dateJSRQ.Enabled = true;
                }
            }
        }

        //加载违章信息
        private void LoadWeiZhangInfo(int czdId)
        {
            var weiZhangInfo = _weiZhangService.GetWeiZhangInfoByChuZuDanId(czdId);
            if (weiZhangInfo.Count > 0)
            {
                var sb = new StringBuilder();
                var i = 1;
                foreach (WeiZhangInfo wz in weiZhangInfo)
                {
                    sb.AppendFormat("===========违章{0}===========\r\n", i);
                    sb.AppendFormat("日期:{0}\r\n内容:{1} {2}\r\n罚金:{3}元\r\n", wz.tWZDate, wz.sWZAddr, wz.sWZDetail, wz.dWZJE);
                    i++;
                }
                txtMore.Text += sb.ToString();
                numWZ.Value = (decimal)weiZhangInfo.Sum(wz => wz.dWZJE);
            }
            else
            {
                numWZ.Value = default(decimal);
                txtMore.Text += "\r\n(该客户无违章记录)";
            }
        }

        //检索客户
        private void txtBoxSearName_TextChanged(object sender, EventArgs e)
        {
            listViewExist.Items.Clear();
            var key = txtBoxSearName.Text;
            foreach (KeHuInfo user in _keHuInfoCache.Where(c => c.sName.Contains(key) || c.sIdCard.Contains(key)))
            {
                var cItem = new ListViewItem();
                cItem.Tag = user.iKeHuId;
                cItem.Text = string.Format("{0}({1})", user.sName, user.sIdCard.Substring(14, 4));
                listViewExist.Items.Add(cItem);
            }
        }

        //提交结算
        private void btnOk_Click(object sender, EventArgs e)
        {
            dateJSRQ_ValueChanged(sender, e);
            if (dateJSRQ.Value.Date == dateStart.Value.Date)
            {
                return;
            }
            if (MessageBox.Show("您确定要退还吗?(Y/N)", "敬告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                try
                {
                    var newTuiHuanInfo = new TuiHuanInfo
                    {
                        iCZDId = (int)labTHInfo.Tag,
                        iKeHuId = (int)txtName.Tag,
                        iCarid = (int)txtCar.Tag,
                        tStartDate = dateStart.Value,
                        tEndDate = dateEnd.Value,
                        tJSRQ = dateJSRQ.Value,
                        iCZDays = (int)numCZDays.Value,
                        iXZDays = (int)numXZDays.Value,
                        dXuZuSF = (double)numXZJE.Value,
                        dYuFuJE = (double)numYuFu.Value,
                        dYaJing = (double)numYJ.Value,
                        dYouHui = (double)numYH.Value,
                        dRiFu = (double)numRF.Value,
                        dYingFu = (double)numYFJE.Value,
                        dShiFu = (double)numSFJE.Value,
                        dWZ = (double)numWZ.Value,
                        dYS = (double)numYS.Value,
                        dYT = (double)numYT.Value,
                        sMore = txtMore.Text,
                        imgKC = pictPhoto.Image.ToBinary()
                    };

                    newTuiHuanInfo = _tuiHuanService.Add(newTuiHuanInfo);
                    //结算成功
                    if (newTuiHuanInfo.iTHDId > 0)
                    {
                        var czdId = (int)labTHInfo.Tag;
                        _chuZuService.Update(czdId, o => o.bCZZF = true);
                        var temp_xz = _xuZuService.Update(czdId, x => x.bXZZF = true);
                        var temp_wz = _weiZhangService.Update(czdId, w => w.bWZZF = true);
                        var temp_kh = _keHuService.Update((int)txtName.Tag, c => { c.bLogout = true; c.tLogoutDate = DateTime.Now; });
                        var sb = new StringBuilder();
                        sb.AppendFormat("客户 {0} 还车完成\r\n", temp_kh.sName);
                        sb.AppendFormat("共有 1 个出租单完成结算\r\n");
                        sb.AppendFormat("共有 {0} 条续租单状态更改为注销\r\n", temp_xz.Count);
                        sb.AppendFormat("共有 {0} 条违章单状态更改为注销\r\n", temp_wz.Count);
                        sb.AppendFormat("客户 {0} 状态已更新为:{1}\r\n", temp_kh.sName, temp_kh.bLogout ? "注销" : "激活");
                        MessageBox.Show(sb.ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        FormTHMana_Load(sender, e);
                    }
                    else
                    {
                        MessageBox.Show("结算成功完成结算操作！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                }
            }
        }

        //修改结算日期
        private void dateJSRQ_ValueChanged(object sender, EventArgs e)
        {
            if (comBoxArea.SelectedIndex == 2)
            {
                return;
            }
            if (DateTime.Now.Date < dateEnd.Value.Date)
            {
                if (MessageBox.Show("该客户未到期,系统将根据您指定的日期计算各项费用!", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    Decimal iDays = Decimal.Round((Decimal)(dateJSRQ.Value.Date - dateStart.Value.Date).TotalDays, 0);
                    numCZDays.Value = iDays;
                    numXZDays.Value = 0;
                }
            }
            else if (DateTime.Now.Date == dateEnd.Value.Date)
            {
                Decimal iDays = Decimal.Round((Decimal)(dateJSRQ.Value.Date - dateStart.Value.Date).TotalDays, 0);
                numCZDays.Value = iDays;
                numXZDays.Value = 0;
            }
            else if (MessageBox.Show("该客户已超期,系统将根据您指定的日期计算各项费用!", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                Decimal iDays = Decimal.Round((Decimal)(dateJSRQ.Value.Date - dateStart.Value.Date).TotalDays, 0);
                numCZDays.Value = iDays;
                numXZDays.Value = 0;
            }
        }

        //当数值改变时重新计算费用
        private void ReCalculateMoney(object sender, EventArgs e)
        {
            CalculateMoney();
        }
    }
}
